package com.ultrapower.ctool.xn_app;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.Gson;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.model.RegisterRolePirVO;
import com.ultrapower.ctool.utils.InstanceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChangeUserInfoActivity extends AppCompatActivity implements View.OnClickListener {

    private Button saveUserInfochangeButton;

    private Button cancleUserInfochangeButton;

    private EditText xm;

    private EditText email;

    private EditText mphone;

    private Spinner pstatus;

    private Spinner zjtype;

    private EditText zjbh;

    private Spinner xb;

    private Spinner post;
    private CustomApplication application;
    //private OkHttpClient client = new OkHttpClient();
    private Gson gson = new Gson();
    private Map<String, EditText> textMap = new HashMap<String, EditText>();
    private Map<String, Spinner> spinnerMap = new HashMap<String, Spinner>();
    private Map<String, Map<String, Object>> resultMap;
    private AdapterView.OnItemSelectedListener OnCatSpinnerCL = new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK);
            ((TextView) parent.getChildAt(0)).setTextSize(18);
        }

        public void onNothingSelected(AdapterView<?> parent) {

        }
    };
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(getApplicationContext(), "用户名详情成功", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case 2:
                    Toast.makeText(getApplicationContext(), "用户名修改成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    intent.setClass(ChangeUserInfoActivity.this, MainActivity.class);
                    ChangeUserInfoActivity.this.startActivity(intent);
                    finish();
                    break;
                case 0:
                    Toast.makeText(getApplicationContext(), "没获得相关数据", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_user_info);
        application = (CustomApplication) getApplication();
        init();
        client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void init() {
        saveUserInfochangeButton = (Button) findViewById(R.id.saveUserInfochange);
        cancleUserInfochangeButton = (Button) findViewById(R.id.cancleUserInfochange);
        xm = (EditText) findViewById(R.id.xm);
        textMap.put("xm", xm);
        email = (EditText) findViewById(R.id.email);
        textMap.put("email", email);
        mphone = (EditText) findViewById(R.id.mphone);
        textMap.put("mphone", mphone);
        pstatus = (Spinner) findViewById(R.id.pstatus);
        spinnerMap.put("pstatus", pstatus);
        zjtype = (Spinner) findViewById(R.id.zjtype);
        spinnerMap.put("zjtype", zjtype);
        zjbh = (EditText) findViewById(R.id.zjbh);
        textMap.put("zjbh", zjbh);
        xb = (Spinner) findViewById(R.id.xb);
        spinnerMap.put("xb", xb);
        post = (Spinner) findViewById(R.id.post);
        spinnerMap.put("post", post);
        saveUserInfochangeButton.setOnClickListener(this);
        cancleUserInfochangeButton.setOnClickListener(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                            .build();
                    Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "user/update/c_pt_user").post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        resultMap = gson.fromJson(result, Map.class);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                for (Map.Entry<String, Object> entry : resultMap.get("result").entrySet()) {
                                    if (textMap.get(entry.getKey()) != null) {
                                        textMap.get(entry.getKey()).setText(entry.getValue().toString());
                                        textMap.get(entry.getKey()).setEnabled ((Boolean) resultMap.get("result").get(entry.getKey()+"_qx"));
                                        textMap.get(entry.getKey()).setFocusable ((Boolean) resultMap.get("result").get(entry.getKey()+"_qx"));

                                    } else {
                                        if (entry.getKey().endsWith("_List") && entry.getValue() instanceof List) {
                                            List<Map<String, Object>> list = (List<Map<String, Object>>) entry.getValue();
                                            List<RegisterRolePirVO> voList = new ArrayList<RegisterRolePirVO>();
                                            for (Map<String, Object> value : list) {
                                                try {
                                                    RegisterRolePirVO vo = (RegisterRolePirVO) InstanceUtil.mapToObject(value, RegisterRolePirVO.class);
                                                    voList.add(vo);
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                            Spinner spinner = spinnerMap.get(entry.getKey().split("_List")[0]);
                                            ArrayAdapter<RegisterRolePirVO> aradapter = new ArrayAdapter<RegisterRolePirVO>(getApplicationContext(), android.R.layout.simple_spinner_item, voList);
                                            aradapter.setDropDownViewResource(R.layout.simple_dropdown_item_1line);
                                            spinner.setAdapter(aradapter);
                                            int k = aradapter.getCount();
                                            for (int i = 0; i < k; i++) {
                                                if (resultMap.get("result").get(entry.getKey().split("_List")[0]).equals(aradapter.getItem(i).getId().toString())) {
                                                    spinner.setSelection(i);
                                                    break;
                                                }
                                            }
                                            spinner.setOnItemSelectedListener(OnCatSpinnerCL);
                                        }
                                    }
                                }
                                for(Map.Entry<String, Spinner> entry1 : spinnerMap.entrySet()){
                                    entry1.getValue().setEnabled ((Boolean) resultMap.get("result").get(entry1.getKey()+"_qx"));
                                    entry1.getValue().setFocusable ((Boolean) resultMap.get("result").get(entry1.getKey()+"_qx"));
                                }
                            }
                        });
                    } else {
                        Message message = new Message();
                        message.what = 0;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.saveUserInfochange:

                String xbId = ((RegisterRolePirVO) xb.getSelectedItem()).getId();    //获取当前输入的用户名和密码信息
                String postId = ((RegisterRolePirVO) post.getSelectedItem()).getId();
                if (xbId.equals("")) {
                    Toast.makeText(getApplicationContext(), "性别不能为空", Toast.LENGTH_SHORT).show();
                } else if (postId.equals("") || "".equals(postId)) {
                    Toast.makeText(getApplicationContext(), "职位不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                OkHttpClient client = new OkHttpClient();
                                FormBody.Builder builder = new FormBody.Builder()
                                        .add("userId", String.valueOf(application.getLoginUser().getLogin_id()));
                                for (Map.Entry<String, EditText> entry : textMap.entrySet()) {
                                    resultMap.get("result").put(entry.getKey(), entry.getValue().getText().toString());
                                }
                                for (Map.Entry<String, Spinner> entry : spinnerMap.entrySet()) {
                                    resultMap.get("result").put(entry.getKey().split("_List")[0], ((RegisterRolePirVO) entry.getValue().getSelectedItem()).getId());
                                }
                                for (Map.Entry<String, Object> entry : resultMap.get("result").entrySet()) {
                                    if (entry.getValue() instanceof String) {
                                        builder.add(entry.getKey(), (String) entry.getValue());
                                    }
                                }
                                RequestBody requestBody = builder.build();
                                Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "form/doUpdate/c_pt_user").post(requestBody).build();
                                Response response = client.newCall(request).execute();
                                if (response.isSuccessful()) {//成功
                                    String result = response.body().string();
                                    System.out.println("result:" + result);
                                    Map<String, Object> resultMap = gson.fromJson(result, Map.class);
                                    if((boolean)resultMap.get("success")) {
                                        Message message = new Message();
                                        message.what = 2;
                                        handler.sendMessage(message);
                                    }
                                } else {
                                    Message message = new Message();
                                    message.what = 0;
                                    handler.sendMessage(message);
                                }
                            } catch (Exception e) {
                                Message message = new Message();
                                message.what = 0;
                                handler.sendMessage(message);
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
                break;
            case R.id.cancleUserInfochange:
                finish();
                break;
        }
    }
}


